<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\home\controller;

use api\index\controller\CommonController;
use app\admin\model\BatMatchModel;
use app\admin\model\BuyContentModel;
use app\admin\model\ChangeCoinModel;
use app\admin\model\FavoriteModel;
use app\admin\model\InfoSetModel;
use app\admin\model\MemberModel;
use app\admin\model\PreResultModel;
use app\admin\model\ReadLookModel;
use app\admin\model\UserModel;
use cmf\controller\RestBaseController;
use app\admin\model\TalkModel;
use think\Request;
use think\Db;

//聊吧
class TalkController extends RestBaseController
{
    public function index(Request $request)
    {
        if (!$request->isPost()) {
            $this->error('请求方式错误');
        }

        $this->checkValidate($request->param(),config('check.type'));
        $member = MemberModel::get($this->getUserId());
        $talk_id = $member->buyContent()->order('create_time desc')->column('talk_id');
        $val = implode(",",$talk_id);//将数组进行转换，重要！！！
        $exp = new \think\db\Expression('field(id,'.$val.')');
        $order = $request->type == 3?$exp:'create_time desc';
        $talks = TalkModel::field('id,title,talk_coin,user_id,type1,buy_num,create_time')
            ->where(function ($query)use($talk_id,$exp,$request){
                if ($request->type == 3){ //已购聊吧
                    $query->whereIn('id',$talk_id);
                }else{
                    $query->where('type', $request->type);
                    $query->whereIn('id',$this->talkIds());
                    $query->order('create_time desc');
                }
            })
            ->with(['user'=>function($query){ //关联专家表
                    $query->field('id,avatar,signature,user_nickname');
                },'preResult'=> function($query){ // 关联预测表
                $query->field('id,bat_id,talk_id');
                $query->with(['bat_match'=>function($query){ //关联对战表
                    $query->field('id,lea_name,team_main_id,team_pass_id,match_time');
                    $query->with(['team_main_name','team_pass_name']);
                }]);
            }])
            ->order($order)
            ->paginate(config('verify.limit'))->each(function($item) use($member){
                //用户是否收藏
                $item->is_favorite = $member->talk_is_favorite($item->id,FavoriteModel::COLLECTION);
                //用户是否购买
                $item->is_buy = $member->buyContent()->where('talk_id',$item->id)->find() ?true :false;
            });
        $this->success('成功', $talks);
    }

    //查询文章关联的对战没有结束的
    public function talkIds()
    {
        $ids = array();
        $bat = BatMatchModel::where('status','<>',BatMatchModel::EVEMT_STATUS_RESULTFUL)->select();
        foreach ($bat as $value){
            if ($pre = PreResultModel::where('bat_id',$value->id)->find()){
                $id = $pre['talk_id'];
                if (! in_array($id,$ids)){
                    $ids[] = $id;
                }
            }
        }
        return $ids;
    }

    /**
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 聊神个人主页
     */
    public function homepage(Request $request)
    {
        if (! $request->isGet()){
            $this->error('请求方式错误');
        }
        $this->checkValidate($request->param(),config('check.id'));
        $limit = config('verify.limit');
        $user = UserModel::where('id',$request->id)
            ->field('id,avatar,signature,desc,fans_num,user_nickname,tag')
            ->with(['talks'=>function($query) use($request,$limit){
                $query->page($request->page,$limit);
                $query->order('create_time desc');
                $query->field('id,title,talk_coin,read_num,praise_num,buy_num,user_id,create_time,type1');
                $query->with(['preResult'=> function($query){ // 关联预测表
                    $query->field('id,bat_id,talk_id');
                    $query->with(['bat_match'=>function($query){ //关联对战表
                        $query->field('id,lea_name,team_main_id,team_pass_id,match_time');
                        $query->with(['team_main_name','team_pass_name']);
                    }]);
                }]);
            }])
            ->find();
        $userInfo = UserModel::get($request->id); //聊神信息
        $member = MemberModel::get($this->getUserId()); //用户信息
        $user->is_attention = $member->users()->where('user_id',$user->id)->find()?true:false; //用户是否关注聊神
        if ($user->talks){
            foreach ($user->talks as $value){
                //用户是否收藏
                $value->is_favorite = $member->talk_is_favorite($value->id,FavoriteModel::COLLECTION);
                //用户是否购买
                $value->is_buy = $member->buyContent()->where('talk_id',$value->id)->find() ?true :false;
            }
        }
        $this->success('成功',['last_page'=>ceil(count($userInfo->talks)/$limit),'user'=>$user]);
    }



    /**
     * @param Request $request
     * 购买聊吧
     */
    public function buy(Request $request)
    {
        if (!$request->isPost()) {
            $this->error('请求方式错误');
        }
        $this->checkValidate($request->param(),config('check.id'));

        if (!$talk = TalkModel::get($request->id)) {
            $this->error('文章不存在');
        }
        $member = MemberModel::get($this->getUserId());
        if ($member->BuyContent()->where('talk_id',$request->id)->find()){
            $this->error('已经购买过了');
        }
        if ($member->talk_coin < $talk->talk_coin) {
            $this->error('聊币不够，请充值。');
        }
        Db::startTrans();
        try {
            $member->buyContent()->save(['talk_id' => $request->id, 'spend_talk_coin' => $talk->talk_coin]);
            $member->setDec('talk_coin',$talk->talk_coin); //用户表减去聊币
            $talk->setInc('buy_num');//增加购买人数
            //修改聊币变动表
            CommonController::changeTalkCoin($member->id,-$talk->talk_coin,$member->talk_coin );
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('购买失败');
        }
        $this->success('购买成功');
    }

    /**
     * @param $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 聊吧文章详情
     */
    public function detail($id)
    {
        if (!$this->request->isGet()) {
            $this->error('请求方式错误');
        }
        $member = MemberModel::get($this->getUserId());

        $talk = TalkModel::where('id',$id)
            ->field('id,title,talk_coin,user_id,content,buy_num,type,type1,read_num,read_time,create_time,praise_num')
            ->with(['preResult'=> function($query){ // 关联预测表
                $query->with(['bat_match'=>function($query){ //关联对战表
                    $query->field('id,lea_name,team_main_id,team_pass_id,real_num,fake_num,match_time');
                    $query->with(['team_main_name','team_pass_name']);
                }]);
            },'user'=>function($query){ //关联专家表
                $query->field('id,avatar,signature,tag,user_nickname');
            },'buyContent'=>function($query){
                $query->field('id,member_id,talk_id');
                $query->with(['member'=>function($query){
                    $query->field('avatar,id');
                }]);
            }])->find();
        $talk->is_buy = true;
        if ($talk->type1  !==  TalkModel::TALK_FREE){
            //判断不是免费的文章有没有购买
            $talk->is_buy = BuyContentModel::where(['member_id'=>$member->id,'talk_id'=>$talk->id])->find()?true:false;
        }
        $talk->is_favorite = $member->talk_is_favorite($talk->id,FavoriteModel::COLLECTION);//有没有收藏
        $talk->is_praise = $member->talk_is_favorite($talk->id,FavoriteModel::PRAISE);//有没有点赞
        $talk->setInc('read_num'); //增加阅读量
        $this->success('成功',$talk);
    }

    /**
     * @param Request $request
     * 阅读文章增加球币
     */
    public function incCoin(Request $request)
    {
        $this->checkValidate($request->param(),config('check.id'));
        $member = MemberModel::get($this->getUserId());
        if ($member->task(ReadLookModel::TYPE_READ)){
            $this->error('今日已完成阅读任务');
        }
        Db::startTrans();
        try {
            $read_coin = InfoSetModel::value('read_coin');

            $member->setInc('coin',$read_coin);
            //球币变动插入数据
            CommonController::changeCoin($member->id,ChangeCoinModel::READ_ARTICLE ,$request->id,'阅读文章','+'.$read_coin, $member->coin);
            //阅读记录插入数据
            $member->readLook()->save(['type'=> ReadLookModel::TYPE_READ,'record_id'=>$request->id]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('失败');
        }
        $this->success('成功');
    }

}
